package org.jsola.contract.service.impl;

import org.jsola.common.StrKit;
import org.jsola.contract.common.ExampleKit;
import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.dao.IContractGroupDAO;
import org.jsola.contract.dto.ContractGroupAddDTO;
import org.jsola.contract.dto.ContractGroupUpdateDTO;
import org.jsola.contract.entity.ContractGroupDO;
import org.jsola.contract.query.CategoryQuery;
import org.jsola.contract.query.ContractGroupQuery;
import org.jsola.contract.service.ICategoryService;
import org.jsola.contract.service.IContractGroupService;
import org.jsola.contract.vo.ContractGroupListVO;
import org.jsola.contract.vo.ContractGroupVO;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.HtmlUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同类型分组
 *
 * @author JanusMix
 */
@Service("contractContractGroupServiceImpl")
public class ContractGroupServiceImpl implements IContractGroupService {

    @Autowired
    private IContractGroupDAO contractGroupDAO;
    @Autowired
    private ICategoryService categoryService;

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public ContractGroupVO save(ContractGroupAddDTO contractGroupAddDTO, TokenUser tokenUser) {
        // 转DO
        ContractGroupDO contractGroupDO = contractGroupAddDTO.to(ContractGroupDO.class);

        String name = contractGroupDO.getName();
        name = name.replaceAll("&nbsp;", " ");
        contractGroupDO.setName(HtmlUtils.htmlUnescape(name));
        // 校验是否重名
        ContractGroupQuery contractGroupQuery = new ContractGroupQuery();
        contractGroupQuery.setName(contractGroupDO.getName());
        contractGroupQuery.setSubjectId(contractGroupDO.getSubjectId());
        Example example = buildExample(contractGroupQuery, tokenUser.getSiteId());
        ParamException.isTrue(CollectionUtils.isEmpty(contractGroupDAO.selectByExample(example)),
                "同一业务中分组名不能重复");
        // 保存
        contractGroupDO = save(contractGroupDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return contractGroupDO.to(ContractGroupVO.class);
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public int update(ContractGroupUpdateDTO contractGroupUpdateDTO, TokenUser tokenUser) {

        ContractGroupVO contractGroupVO = this.selectById(contractGroupUpdateDTO.getId(), tokenUser.getSiteId());
        //转DO
        ContractGroupDO contractGroupDO = contractGroupUpdateDTO.to(ContractGroupDO.class);

        String name = contractGroupDO.getName();
        name = name.replaceAll("&nbsp;", " ");
        contractGroupDO.setName(HtmlUtils.htmlUnescape(name));
        // 校验是否重名
        if (!contractGroupVO.getName().equals(contractGroupDO.getName())) {
            ContractGroupQuery contractGroupQuery = new ContractGroupQuery();
            contractGroupQuery.setName(contractGroupDO.getName());
            contractGroupQuery.setSubjectId(contractGroupDO.getSubjectId());
            Example example = buildExample(contractGroupQuery, tokenUser.getSiteId());
            ParamException.isTrue(CollectionUtils.isEmpty(contractGroupDAO.selectByExample(example)),
                    "同一业务中分组名不能重复");
        }
        //根据主键更新，只更新非null值
        return updateByIdSelective(contractGroupDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, Long... contractGroupIds) {
        return deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) contractGroupIds);
    }


    @Override
    public ContractGroupVO selectById(Long contractGroupId, String siteId) {
        ContractGroupDO contractGroupDO = selectDOById(contractGroupId, siteId);
        if (contractGroupDO == null) {
            return null;
        }
        ContractGroupVO contractGroupVO = contractGroupDO.to(ContractGroupVO.class);
        CategoryQuery categoryQuery = new CategoryQuery();
        categoryQuery.setGroupId(contractGroupDO.getId());
        contractGroupVO.setCategoryCount(categoryService.selectCount(categoryQuery, siteId));
        return contractGroupVO;
    }

    @Override
    public List<ContractGroupListVO> select(ContractGroupQuery contractGroupQuery, TokenUser tokenUser) {
        createDefaultContractGroup(contractGroupQuery.getSubjectId(), tokenUser);
        List<ContractGroupDO> contractGroupDOList = selectDO(contractGroupQuery, tokenUser.getSiteId());
        if (CollectionUtils.isEmpty(contractGroupDOList)) {
            return contractGroupDOList == null ? null : new ArrayList<>();
        }
        List<ContractGroupListVO> resultList = contractGroupDOList.stream()
                .map(contractGroupDO -> contractGroupDO.to(ContractGroupListVO.class))
                .collect(Collectors.toList());
        this.dealCategoryCount(resultList, tokenUser.getSiteId());
        return resultList;
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public void createDefaultContractGroup(String companyId, TokenUser tokenUser) {
        // 查询公司下合同类型分组数量
        Example example = new Example(ContractGroupDO.class);
        example.and().andEqualTo("subjectId", companyId);
        int count = contractGroupDAO.selectCountByExample(example);
        // 没有合同类型分组则创建
        if (count > 0) {
            return;
        }
        ContractGroupAddDTO contractGroupAddDTO = new ContractGroupAddDTO();
        contractGroupAddDTO.setSubjectId(companyId);
        contractGroupAddDTO.setName("默认分组");
        contractGroupAddDTO.setSort(1);
        save(contractGroupAddDTO, tokenUser);
    }

    @Override
    public int selectCount(ContractGroupQuery contractGroupQuery, String siteId) {
        Example example = buildExample(contractGroupQuery, siteId);
        return contractGroupDAO.selectCountByExample(example);
    }

    @Override
    public Page<ContractGroupListVO> selectPage(ContractGroupQuery contractGroupQuery, String siteId) {
        Example example = buildExample(contractGroupQuery, siteId);
        Page<ContractGroupDO> page = contractGroupDAO.selectPageByExample(example,
                contractGroupQuery.getPageNo(),
                contractGroupQuery.getPageSize());

        Page<ContractGroupListVO> resultPage = page.to(ContractGroupListVO.class);
        List<ContractGroupListVO> resultList = resultPage.getEntities();
        this.dealCategoryCount(resultList, siteId);
        return resultPage;
    }

    @Override
    public ContractGroupDO selectDOById(Long contractGroupId, String siteId) {
        return listById(contractGroupId, siteId);
    }

    @Override
    public List<ContractGroupDO> selectDO(ContractGroupQuery contractGroupQuery, String siteId) {
        Example example = buildExample(contractGroupQuery, siteId);
        return contractGroupDAO.selectByExample(example);
    }

    @Override
    public List<ContractGroupDO> selectBySubjectId(String subjectId, TokenUser tokenUser) {
        Example example = new Example(ContractGroupDO.class);
        example.and()
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("subjectId", subjectId);
        return contractGroupDAO.selectByExample(example);
    }

    @Override
    public List<ContractGroupDO> selectIsSystem(String siteId) {
        Example example = new Example(ContractGroupDO.class);
        example.and()
                .andEqualTo("siteId", siteId)
                .andEqualTo("isSystem", Boolean.TRUE);
        return contractGroupDAO.selectByExample(example);
    }

    @Override
    public List<ContractGroupDO> selectIsSystemNotSiteId() {
        Example example = new Example(ContractGroupDO.class);
        example.and()
                .andEqualTo("isSystem", Boolean.TRUE);
        return contractGroupDAO.selectByExample(example);
    }

    @Override
    public List<ContractGroupDO> selectBySubjectIdAndNames(String subjectId, List<String> names) {
        if (CollectionUtils.isEmpty(names)) {
            return new ArrayList<>();
        }
        Example example = new Example(ContractGroupDO.class);
        example.and()
                .andEqualTo("subjectId", subjectId)
                .andIn("name", names);
        return contractGroupDAO.selectByExample(example);
    }

    /**
     * 处理分组下合同类型数
     *
     * @param resultList list
     * @param siteId     站点id
     */
    private void dealCategoryCount(List<ContractGroupListVO> resultList, String siteId) {
        for (ContractGroupListVO contractGroupListVO : resultList) {
            CategoryQuery categoryQuery = new CategoryQuery();
            categoryQuery.setGroupId(contractGroupListVO.getId());
            categoryQuery.setValid(Boolean.TRUE);
            contractGroupListVO.setCategoryCount(categoryService.selectCount(categoryQuery, siteId));
        }
    }


    /**
     * 根据查询参数，构建example
     *
     * @param contractGroupQuery 查询参数
     * @param siteId             所属站点id
     * @return example
     */
    private Example buildExample(ContractGroupQuery contractGroupQuery, String siteId) {
        Example example = new Example(ContractGroupDO.class);
        example.and()
                .andEqualTo("siteId", siteId);
        if (contractGroupQuery.getName() != null) {
            example.and().andEqualTo("name", contractGroupQuery.getName());
        }
        if (contractGroupQuery.getSubjectId() != null) {
            example.and().andEqualTo("subjectId", contractGroupQuery.getSubjectId());
        }
        if (contractGroupQuery.getSort() != null) {
            example.and().andEqualTo("sort", contractGroupQuery.getSort());
        }
        // 排序
        ExampleKit.setExampleOrder(example, contractGroupQuery.getOrders());
        return example;
    }
}




